<template>
    <label class="mo-upload">
        <input type="file" :accept="accepts" @change="upload">
        <slot></slot>
        <span class="uploadSpan">
          <img src="@/assets/images/add@2x.png" alt="">
        </span>
    </label>
</template>
<style lang="scss">
    .mo-upload {
        display: inline-block;
        position: relative;
        margin-bottom: 0;
        width: 100%;
        input[type="file"] {
            display: none;
        }
        .mo-upload--label {
            display: inline-block;
            position: relative;
        }
    }
    .uploadSpan{
      width: 100%;
      height: 148px;
      display: block;
      position: relative;
      border-radius: 4px;
      background: $eeeColor;
      text-align: center;
      line-height: 148px;
    }
</style>
<script>
  import axios from 'axios';
  import {mapState} from 'vuex';    //vuex
  import {MessageBox} from 'mint-ui';
  import Qiniu from 'qiniu-js';


    export default {
        name : 'MoUpload',
        props : {
            accepts : { //允许的上传类型
                type : String,
                default : 'image/jpeg,image/jpg,image/png,image/gif'
            },
            flag : [String, Number], //当前上传标识,以便于在同一个监听函数中区分不同的上传域
            maxSize : {
                type : Number,
                default : 0 //上传大小限制
            },
        },
        data: () => ({
          files: [], // 文件
          uptokenObj:'',
        }),
        computed:{
          //这里的三点叫做 : 扩展运算符
          ...mapState({
            uploadToken:state=>state.upload.uploadToken,
            token: state=>state.login.token,
            // 相当于
            //show(){
            //     return this.$store.state.dialog.show;
            // }
          }),
        },
        methods: {

            upload (event) {
                let file = event.target.files[0]
                const self = this
                const flag = this.flag
                if (file) {
                    if (this.maxSize) {
                        //todo filter file
                    }
                    //filter file, 文件大小,类型等过滤
                    //如果是图片文件
                    // const reader = new FileReader()
                    // const imageUrl = reader.readAsDataURL(file)
                    // img.src = imageUrl //在预览区域插入图片

                    const formData = new FormData()
                    formData.append('file', file)

                    let userInfo = JSON.parse(window.localStorage.getItem('userInfo'));
                    let token = window.localStorage.getItem('userToken');
                    // console.log(userInfo.token);
                    //获取token
                    axios.get(configUrl.GETUPLOADTOKEN_URL,
                    {
                      headers:{
                				'token':token
                			}
                    })  //获取七牛token
                    .then(response => {
                        console.log(response);
                        if(response.data.code==401){
                          MessageBox.alert('授权过期，请重新登录').then(action => {
                              self.$router.push({name:'login'});
                            }).catch(err=>{
                              console.log(err);
                            });
                        }else{
                          const uploadResult = response.data.data;
                          formData.append('token', uploadResult.token);
                          // formData.append('key', result.key)
                          //提交给七牛处理
                          axios.post('http://upload-z2.qiniup.com', formData, {
                              progress(event) {
                                  //传递给父组件的progress方法
                                  self.$emit('progress', parseFloat(event.loaded / event.total * 100), flag)
                              }
                          })
                          .then(response => {
                              console.log(response);
                              const result = response.data;
                              if (result.hash && result.key) {
                                  //传递给父组件的complete方法
                                  self.$emit('complete', 200 , result, uploadResult, flag)
                                  //让当前target可以重新选择
                                  event.target.value = null
                              } else {
                                  self.$emit('complete', 500, result, flag)
                              }
                          }, error => self.$emit('complete', 500, error.message), flag)
                        }

                    })
                }
            }
        },
        mounted() {
          //do something after mounting vue instance

        }
    }
</script>
